#!/usr/bin/env perl

BEGIN
{
    unshift(@INC, '.');
    require Data::Dumper;
    require LifeRay;
}

sub read_sets()
{
    my @tag_sets = LifeRay::query('SELECT vocabularyId, name, description FROM tagsvocabulary');
    die if grep($_->{description}, @tag_sets);
    return map(($_->{vocabularyId} => { NAME => $_->{name} }), @tag_sets);
}

sub read_tags($)
{
    my ($sets) = @_;
    my @tags = LifeRay::query('SELECT vocabularyId, entryId, name FROM tagsentry');
    foreach my $tag (@tags)
    {
	die if (!exists($sets->{$tag->{vocabularyId}}));
	my $set = $sets->{$tag->{vocabularyId}};
	$set->{TAGS}{$tag->{entryId}} = $tag->{name};
    }
}


my %sets = read_sets();
read_tags(\%sets);

foreach my $set_id (sort { $sets{$a}{NAME} cmp $sets{$b}{NAME} } keys(%sets))
{
    my $set = $sets{$set_id};
    print "$set_id  $set->{NAME}\n";
    foreach my $tag_id (sort { $set->{TAGS}{$a} cmp $set->{TAGS}{$b} } keys(%{$set->{TAGS}})) {
	print "$tag_id    $set->{TAGS}{$tag_id}\n";
    }
}
